package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entity.CommonResult;
import com.atguigu.springcloud.entity.Payment;
import com.atguigu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;


/**
 * @author Tu
 * @date 2022/12/26 16:20
 */
@Slf4j
@RestController
@RequestMapping(value = "/api/v1/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;

    @GetMapping("/selById/{id}")
    public CommonResult selPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.selPaymentById(id);
        if (null != payment) {
            return new CommonResult(200, "查询成功，端口号" + serverPort, payment);
        } else {
            return new CommonResult(444, "没有对应记录");
        }
    }

    @PostMapping(value = "/insert")
    public CommonResult insertPayment(@RequestBody Payment payment) {
        int result = paymentService.insertPayment(payment);
        log.info("插入数据成功，返回状态：{}", result);
        if (result > 0) {
            return new CommonResult(200, "插入成功，端口号" + serverPort, result);
        } else {
            return new CommonResult(444, "插入失败");
        }
    }

    @RequestMapping(method = RequestMethod.GET, value = "/serverPort")
    public String getServerPort() {
        return serverPort;
    }

    /**
     * 模拟feignClient调用超时
     *
     * @return
     */
    @GetMapping(value = "/timeout")
    public String paymentFeignTimeout() {
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serverPort;
    }

}
